package com.jml.zlhq.app.ui;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jml.zlhq.app.BuildConfig;
import com.jml.zlhq.app.R;
import com.jml.zlhq.app.URLs;
import com.jml.zlhq.app.service.HttpService;
import com.jml.zlhq.app.ui.WebAppInterface.webCallBack;
import com.jml.zlhq.app.util.BaseTools;
import com.jml.zlhq.app.util.UIUtil;
import com.jml.zlhq.app.widgets.FoundWebView;
import com.jml.zlhq.app.widgets.FoundWebView.ScrollInterface;
import com.loopj.android.http.TextHttpResponseHandler;

@SuppressWarnings("deprecation")
public class ShangjiaActivity extends BaseActivity {
	private FoundWebView webView;
	private LinearLayout pinglun,phone;
	private LinearLayout loadpage;
	private TextView loadText;
	private RelativeLayout header;
	private int topPicH;
	private String url;
	private String id;
	private Handler handler = new Handler() {  
        @Override  
        public void handleMessage(Message msg) {  
        		Log.i("==web url==", url);
        		if(msg.what==1){
        			fx.setImageResource(collected?R.drawable.ico_save_full:R.drawable.collect_selector);
        		}
                if(msg.what!=200) {//主页不存在  
                    //载入本地assets文件夹下面的错误提示页面404.html  
                	loadText.setText("很抱歉，出错啦！"); 
                } else {  
                	webView.loadUrl(url);  
                }  
        }  
	}; 
	public webCallBack share,collect,info;
	private String infoStr;
	private boolean collected = false;
	private ImageView fx;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.shangjia_detail_activity);
		
		topPicH = (int) (UIUtil.winWidth*336/640-getResources().getDimension(R.dimen.header_hight));
		
		LinearLayout leftLay = (LinearLayout) findViewById(R.id.content_header_left_lay);
		LinearLayout rightLay = (LinearLayout) findViewById(R.id.content_header_right_lay);
		leftLay.setOnClickListener(this);
		rightLay.setOnClickListener(this);
		AutoCompleteTextView centerEdit = (AutoCompleteTextView) findViewById(R.id.content_header_center_edit);
		centerEdit.setVisibility(View.GONE);
		ImageView leftImage = (ImageView) findViewById(R.id.content_header_left_img);
		leftImage.setImageResource(R.drawable.back_selector);
		ImageView roghtImage1 = (ImageView) findViewById(R.id.content_header_right_img);
		roghtImage1.setImageResource(R.drawable.share_selector);
		fx = (ImageView) findViewById(R.id.content_header_right_img2);
		fx.setVisibility(View.VISIBLE);
		fx.setImageResource(R.drawable.collect_selector);
		TextView centerText = (TextView) findViewById(R.id.content_header_center_text);
		centerText.setVisibility(View.INVISIBLE);
		TextView rightText = (TextView) findViewById(R.id.content_header_right_text);
		rightText.setVisibility(View.INVISIBLE);
		TextView cityChosed = (TextView) findViewById(R.id.content_header_center_text2);
		cityChosed.setVisibility(View.GONE);
		loadpage = (LinearLayout)findViewById(R.id.load_info_lay);
		loadText = (TextView) findViewById(R.id.load_info);
		loadpage.setVisibility(View.VISIBLE);
		
		roghtImage1.setOnClickListener(this);
		fx.setOnClickListener(this);
		
		header = (RelativeLayout) findViewById(R.id.content_header);
		header.setBackgroundColor(getResources().getColor(R.color.black));
		header.getBackground().setAlpha(0);
		
		ImageView spaceshipImage = new ImageView(this);
		spaceshipImage.setImageResource(R.drawable.publicloading);
		Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(this, R.anim.loading_animation);
		loadpage.addView(spaceshipImage, 0);
		spaceshipImage.startAnimation(hyperspaceJumpAnimation);
		
		webView = (FoundWebView) findViewById(R.id.shangjia_detail_web);
		pinglun = (LinearLayout) findViewById(R.id.shangjia_detail_pinglun);
		phone = (LinearLayout) findViewById(R.id.shangjia_detail_shop);
				
		pinglun.setOnClickListener(this);
		phone.setOnClickListener(this);
		
		this.initWebView();
		
		webView.setOnCustomScroolChangeListener(new ScrollInterface() {
			@Override
			public void onSChanged(int l, int t, int oldl, int oldt) {
				int alpha = t*255/topPicH;
				alpha = alpha>220?220:alpha;
				alpha = alpha<0?0:alpha;
				header.getBackground().setAlpha(alpha);
			}
		});
		
		//if()
		//if(crowdUrl!=null&&crowdUrl.contains("/map"))crowdUrl = "http://192.168.1.254:8080/"+crowdUrl.substring(crowdUrl.indexOf("/map"));
		try {
			url = getIntent().getExtras().getString("url");
			if(appContext.isLogin())url = url+"&auth_token="+appContext.getLoginUid();
			id = getIntent().getExtras().getString("id");
		} catch (Exception e) {
			e.printStackTrace();
		}
		new Thread(new Runnable() {  
            @Override  
            public void run() {  
                    Message msg = new Message();  
                    //此处判断主页是否存在，因为主页是通过loadUrl加载的，  
                    //此时不会执行shouldOverrideUrlLoading进行页面是否存在的判断  
                    //进入主页后，点主页里面的链接，链接到其他页面就一定会执行shouldOverrideUrlLoading方法了  
                    msg.what = getRespStatus(url);  
                    handler.sendMessage(msg);  
            }  
		}).start();  
		share = new webCallBack() {
			@Override
			public void call(Object str) {
				UIUtil.showLoadingDialog(ShangjiaActivity.this, "加载中，请稍后...", false);
				appContext.showShare(URLs.SHARE_TEAM+"?id="+id);
			}
		};
		collect = new webCallBack() {
			@Override
			public void call(Object str) {
				if(!appContext.isLogin()){
					UIUtil.openActivity(ShangjiaActivity.this, LoginActivity.class, null,1);
				}else{
					Map<String, String> map = new HashMap<String, String>();
					map.put("auth_token", appContext.getLoginUid());
					map.put("target_id", id);
					final Dialog  mProDialog =  UIUtil.showLoadingDialog(activity, "提交中，请稍后...", false);
					HttpService.postByText(collected?URLs.COLLECT_CANCEL_TEAM:URLs.COLLECT_TEAM, map, new TextHttpResponseHandler() {
						
						@Override
						public void onSuccess(int arg0, Header[] arg1, String arg2) {
							mProDialog.dismiss();
							try {
								JSONObject result = new JSONObject(arg2);
								if(result.getInt("status")==0){
									UIUtil.ToastMessage(activity, collected?"取消收藏成功":"收藏成功");
									collected = !collected;
									handler.sendEmptyMessage(1);
									
								}else{
									UIUtil.ToastMessage(activity, result.getString("message"));
								}
							} catch (JSONException e) {
								e.printStackTrace();
								UIUtil.ToastMessage(activity, collected?"取消收藏失败":"收藏失败");
							}
						}
						
						@Override
						public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
							mProDialog.dismiss();
							UIUtil.ToastMessage(activity, collected?"取消收藏失败":"收藏失败");
						}
					});
				}
			}
		};
		info = new webCallBack() {
			
			@Override
			public void call(Object obj) {
				infoStr = obj!=null?obj.toString():null;
				try {
					JSONObject json = new JSONObject(infoStr);
					collected = BaseTools.getFrom("collection_type", json).equals("true");
					if(collected)fx.setImageResource(R.drawable.ico_save_full);
				} catch (Exception e) {}
			}
		};
		// 用JavaScript调用Android函数：
		// 先建立桥梁类，将要调用的Android代码写入桥梁类的public函数
		// 绑定桥梁类和WebView中运行的JavaScript代码
		// 将一个对象起一个别名传入，在JS代码中用这个别名代替这个对象，可以调用这个对象的一些方法
		webView.addJavascriptInterface(new WebAppInterface(this,share,collect,info), "appInterface");
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode==1&&appContext.isLogin()){
			url = url+"&auth_token="+appContext.getLoginUid();
			Log.i("==web url==", url);
			webView.loadUrl(url);  
		}
		if(requestCode==2&&resultCode==Activity.RESULT_OK&&null!=data){
			handler.post(new Runnable() {
				@Override
				public void run() {
					if(BuildConfig.DEBUG)Log.i("==comment==", data.getStringExtra("comment"));
					webView.loadUrl("javascript:newComment('"+data.getStringExtra("comment")+"')");
				}
			});
		}
	}

	@Override
	public void loadData(Map<String, String> param) {}

	@Override
	public void clearData() {}
	
	@SuppressLint("SetJavaScriptEnabled")
	private void initWebView(){
		// 得到设置属性的对象
		WebSettings webSettings = webView.getSettings();
		// 使能JavaScript
		webSettings.setJavaScriptEnabled(true);
		// 支持中文，否则页面中中文显示乱码
		webSettings.setDefaultTextEncodingName("UTF-8");
        webSettings.setSaveFormData(false);  
        webSettings.setSupportZoom(false);  
        webSettings.setBlockNetworkImage(true);
		clearCach(webView);
		// 限制在WebView中打开网页，而不用默认浏览器
        webView.setHorizontalScrollBarEnabled(false);//水平不显示
        webView.setVerticalScrollBarEnabled(false); //垂直不显示
        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); 
		webView.setWebViewClient(new WebViewClient(){
			 @Override  
		     public boolean shouldOverrideUrlLoading(WebView view, String url) {  
				 return true;  
			 }  
		});
		// 如果不设置这个，JS代码中的按钮会显示，但是按下去却不弹出对话框
		// Sets the chrome handler. This is an implementation of WebChromeClient
		// for use in handling JavaScript dialogs, favicons, titles, and the
		// progress. This will replace the current handler.
		webView.setWebChromeClient(new EXWebChromeClient());
	}

	protected void clearCach(WebView webView) {
		webView.clearCache(true); 
		CookieSyncManager.createInstance(this);
		CookieManager cookieManager = CookieManager.getInstance();
		cookieManager.removeAllCookie();
		CookieManager.getInstance().removeSessionCookie();
		CookieSyncManager.getInstance().sync();
		CookieSyncManager.getInstance().startSync();
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.content_header_left_lay:
			finish();
			break;
		case R.id.shangjia_detail_pinglun:
			Bundle bdl = new Bundle();
			bdl.putInt("type", 2);
			bdl.putString("id", id);
			UIUtil.openActivity(this, PinglunActivity.class, bdl, 2);
			break;
		case R.id.content_header_right_img:
			if(share!=null)share.call(null);
			break;
		case R.id.shangjia_detail_shop:
			try {
				JSONObject json = new JSONObject(infoStr);
				String phoneString=BaseTools.getFrom("tel", json);
				Intent intent=new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+phoneString));
//				intent.setAction("android.intent.action.CALL");
//				intent.addCategory("android.intent.category.DEFAULT");
				startActivity(intent);
			} catch (Exception e) {
				UIUtil.ToastMessage(activity, "无法获取商家联系方式");
			}
			break;
		case R.id.content_header_right_img2:
			if(collect!=null)collect.call(null);
			break;
		default:
			break;
		}
	}
	
	/** 
     * 继承WebChromeClient类 
     * 对js弹出框时间进行处理 
     *  
     */  
    private class EXWebChromeClient extends WebChromeClient {  
  
        /** 
         * 处理alert弹出框 
         */  
        @Override  
        public boolean onJsAlert(WebView view,String url, String message, JsResult result) {  
//            mReusultText.setText("Alert:"+message);  
//            //对alert的简单封装  
//            new AlertDialog.Builder(WebViewDemo.this).  
//                setTitle("Alert").setMessage(message).setPositiveButton("OK",  
//                new DialogInterface.OnClickListener() {  
//                    @Override  
//                    public void onClick(DialogInterface arg0, int arg1) {  
//                       //TODO  
//                   }  
//            }).create().show();  
//            result.confirm();  
            return super.onJsAlert(view, url, message, result);  
        }  
  
        /** 
         * 处理confirm弹出框 
         */  
        @Override  
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {  
//            mReusultText.setText("Confirm:"+message);  
//            result.confirm();  
            return super.onJsConfirm(view, url, message, result);  
        }  
  
        /** 
         * 处理prompt弹出框 
         */  
        @Override  
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {  
//            mReusultText.setText("Prompt input is :"+message);  
//            result.confirm();  
            return super.onJsPrompt(view, url, message, message, result);  
        }  
        
        @Override
        public void onProgressChanged(WebView view,int newProgress){
        	loadText.setText("玩命加载中\t"+newProgress+"%");
        	if(newProgress>=100){
        		header.getBackground().setAlpha(0);//(activity.getResources().getColor(R.color.full_transparent));
        		loadpage.setVisibility(View.GONE);
        		webView.getSettings().setBlockNetworkImage(false);
        	}
        }
    }  
	
	/**
	 * 自定义的Android代码和JavaScript代码之间的桥梁类
	 * 
	 * @author 1
	 * 
	 */
//	public class WebAppInterface {
//		Context mContext;
//
//		/** Instantiate the interface and set the context */
//		WebAppInterface(Context c) {
//			mContext = c;
//		}
//
//		/** Show a toast from the web page */
//		// 如果target 大于等于API 17，则需要加上如下注解window.thirdLogin.login(param)
//		@JavascriptInterface
//		public void method(String type,String id) {
//			Log.i("====js====", type+","+id);
//		}
//	}
	
	private int getRespStatus(String url) {  
        int status = -1;  
        try {  
                HttpHead head = new HttpHead(url);  
                HttpClient client = new DefaultHttpClient();  
                HttpResponse resp = client.execute(head);  
                status = resp.getStatusLine().getStatusCode();  
        } catch (Exception e) {}  
        return status;  
	} 

}
